<?php

namespace app\admin\model\finance\extract;

use think\Model;
use app\admin\model\AuthDepartment;
use think\Cache;

class Week extends Model
{
    // 表名
    protected $name = 'finance_extract_week';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    
    // 追加属性
    protected $append = [
      
		'division_method_text',
		'division_method_round_text',
		
		'integral_accident_text',
		'integral_complaint_text',
		'integral_subtraction_text',

        'status_tu_text',
        'status_url_text',
        'username_text',
        'status_text',
        'department_text',
        //收入
        'income_text',
        //支出
        'expenses_text',
        //结余
        'balance_text',
        'week_text',
        'lecturer_text',
        'lecturer_avatar_text',
    ];
    
    /**
     * 讲师头像
     */
    public function getLecturerAvatarTextAttr($value, $data){
        $value = $value ? $value : $data['lecturer_id'];
        $avatar = TableField('Admin','thumb_avatar',$value,'userid');
        $avatar = $avatar ? $avatar : TableField('Admin','avatar',$value,'userid');
        $avatar = $avatar ? $avatar : '/dailybill/img/jia.png';
        return $avatar;
    }    
       /**
     * 讲师姓名
     */
    public function getLecturerTextAttr($value, $data){
        $value = $value ? $value : $data['lecturer_id'];
        $username = TableField('Admin','username',$value,'userid');
        return $username;
    }   
     /**
     * 获取周收入
     */
    public function getWeekTextAttr($value, $data){

        if(!$data['week']) $data['week'] = GetYearWeekOne(date('Y',strtotime($data['start_time'])),$data['start_time']);
        return $data['week'];
    } 
    /**
     * 获取周收入
     */
    public function getIncomeTextAttr($value, $data){
        $value = $value ? $value : $data['id'];
        $count = model(GetTableModel('Books'))::field('sum(price) as total')->where(['extract_week'=>$value,'pay_type'=>1])->select();
        return $count[0]['total']?:'0.00';
    }
     /**
     * 获取周支出
     */
    public function getExpensesTextAttr($value, $data){
         $value = $value ? $value : $data['id'];
        $count = model(GetTableModel('Books'))::field('sum(price) as total')->where(['extract_week'=>$value,'pay_type'=>2])->select();
        return $count[0]['total']?:'0.00';
    }    
  /**
     * 结余
     */
    public function getBalanceTextAttr($value, $data){
        return Rounding($this->getIncomeTextAttr($value,$data)-$this->getExpensesTextAttr($value,$data));
    }
   public function getStatusUrlList()
    {
        return [0=>'/index/plan/edit/ids/',1=>'/index/plan/details/ids/',-1=>'/index/plan/edit/ids/',2=>'/index/plan/view/ids/',3=>'/index/plan/view/ids/',-2=>'/index/plan/view/ids/',4=>'/index/plan/view/ids/'];
    } 
    public function getStatusUrlTextAttr($value, $data)
    {
        $value = $value ? $value : $data['status'];
        $list = $this->getStatusUrlList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    public function getStatusList()
    {
        return [0=>'草稿',1=>'初审中',-1=>'初审驳回',2=>'初审通过',3=>'终审中',-2=>'终审驳回',4=>'终审完成'];
    } 
    public function getStatustubiaoList()
    {
        return [-1=>'bohui',-2=>'bohui',0=>'caogao',1=>'submit',2=>'pass',3=>'submit',4=>'finish'];
    }
    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : $data['status'];
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }  
    public function getStatusTuTextAttr($value, $data)
    {
        $value = $value ? $value : $data['status'];
        $list = $this->getStatustubiaoList();
        return isset($list[$value]) ? $list[$value] : '';
    }

     public function getUsernameTextAttr($value, $data){   
        $value = $value ? $value : $data['z_publish'];
        return TableField('Admin','username',$value,'userid');
    }

    public function log()
    {
        return $this->belongsTo('app\admin\model\finance\extract\Weeklog', 'id', 'extract_week', [], 'LEFT')->setEagerlyType(0);
    }

    public function getDivisionMethodList()
    {
        return ['1' => __('Division_method 1'),'2' => __('Division_method 2')];
    }     
    public function getDivisionMethodRoundList()
    {
        return ['1' => __('Division_method_round 1'),'2' => __('Division_method_round 2')];
    }     
    public function getIntegralAccidentList()
    {
        return ['1' => __('Integral_accident 1'),'2' => __('Integral_accident 2')];
    }     
    public function getIntegralComplaintList()
    {
        return ['1' => __('Integral_complaint 1'),'2' => __('Integral_complaint 2')];
    }     
    public function getIntegralSubtractionList()
    {
        return ['1' => __('Integral_subtraction 1'),'2' => __('Integral_subtraction 2'),'3' => __('Integral_subtraction 3'),'4' => __('Integral_subtraction 4'),'5' => __('Integral_subtraction 5')];
    }     


    public function getDivisionMethodTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['division_method'];
        $list = $this->getDivisionMethodList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    public function getDivisionMethodRoundTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['division_method_round'];
        $list = $this->getDivisionMethodRoundList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    public function getIntegralAccidentTextAttr($value, $data){
         $value = $value ? $value : $data['integral_accident'];
        $list = $this->getIntegralAccidentList();
        return isset($list[$value]) ? $list[$value] : '';
    }  
    public function getIntegralComplaintTextAttr($value, $data){
         $value = $value ? $value : $data['integral_complaint'];
        $list = $this->getIntegralComplaintList();
        return isset($list[$value]) ? $list[$value] : '';
    }  
    public function getIntegralSubtractionTextAttr($value, $data){
        $value = $value ? $value : $data['integral_subtraction'];
		$value = explode(",",$value);
		$list = $this->getIntegralSubtractionList();
		$data = '';
	    foreach($value as $key=>$val){
			$name = isset($list[$val]) ? $list[$val] : '';
			if(!empty($name)) $data .= $name.',';
		}
		return trim($data,",");
    }  
	public function getDepartmentList(){
        return array_column(collection(model(GetTableModel('AuthDepartment'))::field('id,name,delete_status')->where('id','in',implode(',', GetBaseInfo('Dept')))->select())->toArray(), 'name','id');
    }
    public function getDepartmentTextAttr($value, $data)
    {
        $value = $value ? $value : $data['department'];
        $list = $this->getDepartmentList();
        $arr = explode(',',$value);
        $str = [];
        foreach ($arr as $value)
        {
            if(isset($list[$value])){
                $str[] = $list[$value];
            }
        }
        $str  = implode(',', $str);
        return  $str;
    }

    /**
     * YangLiu  获取登录用户的分公司，周，时间，数据
     * @param $departmentId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getWeek($departmentId)
    {

        $departmentList = array();
        $departmentId = explode(',',$departmentId);
        foreach ($departmentId as $value)
        {
            AuthDepartment::getChild($departmentList,$value,1);
        }
        $departmentId = implode(',',array_merge($departmentList,$departmentId));

        $where = 'department  in ('.$departmentId.') ' ;

        $join = [
            ['hdyj_auth_department w','a.department=w.id'],
        ];
        $field = 'a.id,a.name,a.status,a.division_method,a.division_method_round,a.department';
        $weeklist = self::alias('a')->join($join)->where($where)->field($field)->select()->toArray();
        $array = [];
        $department = [];
        foreach ($weeklist as $value)
        {
            $array[$value['id']] = $value['department_text'].'--'.$value['name'];
            $department[$value['department']] = $value['department_text'];
        }
        return ['weekList'=>$array,'department'=>$department];
    }

    public static function getName($id)
    {
        if(!$weekList = Cache::get('WEEKLIST'))
        {
            $weeklist = self::field("id,name,status,division_method_round,division_method,department,integral_accident,integral_complaint,integral_subtraction")->select()->toArray();
            $weeklist = array_column($weeklist,null,'id');
            Cache::set('WEEKLIST',$weeklist,604800);//有效期一个星期
        }
        return $weekList[$id]['name'];
    }
}
